package com.seehack.sample.springrest.httpclient;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

public class RequestConfigClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {

    private boolean canOverwriteTimeout = false;
    private int socketTimeout;
    private int connectRequestTimeout;
    private int connectTimeout;

    public RequestConfigClientHttpRequestFactory(CloseableHttpClient httpClient) {
        super(httpClient);
    }

    @Override
    final protected void postProcessHttpRequest(HttpUriRequest request) {
        if (!canOverwriteTimeout) {
            return;
        }
        if (request instanceof HttpRequestBase) {
            HttpRequestBase httpRequestBase = (HttpRequestBase) request;
            RequestConfig requestConfig = httpRequestBase.getConfig();
            RequestConfig.Builder builder = requestConfig == null ?
                    RequestConfig.custom() :
                    RequestConfig.copy(requestConfig);
            builder.setSocketTimeout(socketTimeout)
                    .setConnectTimeout(connectTimeout)
                    .setConnectionRequestTimeout(connectRequestTimeout);
            httpRequestBase.setConfig(builder.build());
        }
    }

    public void setOverwriteSocketTimeout(int socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public void setOverwriteConnectRequestTimeout(int connectRequestTimeout) {
        this.connectRequestTimeout = connectRequestTimeout;
    }

    public void setOverwriteConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public void setCanOverwriteTimeout(boolean canOverwriteTimeout) {
        this.canOverwriteTimeout = canOverwriteTimeout;
    }
}
